<template>
  <div class="user-analytics">
    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total-icon">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalUsers }}</div>
              <div class="stat-label">用户总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon active-icon">
              <i class="el-icon-s-data"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.activeUsers }}</div>
              <div class="stat-label">活跃用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon avg-icon">
              <i class="el-icon-time"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.avgStudyTime }}</div>
              <div class="stat-label">平均学习时长</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon retention-icon">
              <i class="el-icon-s-marketing"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.retentionRate }}%</div>
              <div class="stat-label">用户留存率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 学习时长趋势 -->
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>学习时长趋势</span>
          </div>
          <div class="chart-container">
            <div ref="studyTimeChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 用户活跃度分布 -->
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>用户活跃度分布</span>
          </div>
          <div class="chart-container">
            <div ref="activityChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 学习排行榜 -->
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>学习排行榜</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="viewFullRanking">
              查看完整排行
            </el-button>
          </div>
          <el-table :data="learningRanking" style="width: 100%">
            <el-table-column prop="rank" label="排名" width="60" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.rank <= 3" :class="`rank-badge rank-${scope.row.rank}`">
                  {{ scope.row.rank }}
                </span>
                <span v-else>{{ scope.row.rank }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="nickname" label="用户" width="120"></el-table-column>
            <el-table-column prop="studyTime" label="学习时长" width="100">
              <template slot-scope="scope">
                {{ formatStudyTime(scope.row.studyTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="questionCount" label="做题数" width="80" align="center"></el-table-column>
            <el-table-column prop="correctRate" label="正确率" width="80" align="center">
              <template slot-scope="scope">
                <span :style="{ color: scope.row.correctRate >= 80 ? '#67C23A' : scope.row.correctRate >= 60 ? '#E6A23C' : '#F56C6C' }">
                  {{ scope.row.correctRate }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <!-- 学习进度统计 -->
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>学习进度统计</span>
          </div>
          <div class="progress-stats">
            <div class="progress-item" v-for="(progress, index) in progressStats" :key="index">
              <div class="progress-header">
                <span class="progress-label">{{ progress.category }}</span>
                <span class="progress-percentage">{{ progress.completionRate }}%</span>
              </div>
              <el-progress 
                :percentage="progress.completionRate" 
                :stroke-width="8"
                :color="progress.color"
              ></el-progress>
              <div class="progress-detail">
                <span>已完成: {{ progress.completed }}/{{ progress.total }}</span>
                <span>平均用时: {{ progress.avgTime }}分钟</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 用户学习详情 -->
      <el-col :span="24">
        <el-card>
          <div slot="header">
            <span>用户学习详情</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="exportUserData">
              导出数据
            </el-button>
          </div>
          
          <!-- 筛选条件 -->
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="6">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索用户昵称/邮箱"
                prefix-icon="el-icon-search"
                clearable
              ></el-input>
            </el-col>
            <el-col :span="4">
              <el-select v-model="filterLevel" placeholder="选择等级" clearable>
                <el-option label="新手" value="beginner"></el-option>
                <el-option label="进阶" value="intermediate"></el-option>
                <el-option label="高级" value="advanced"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="filterActivity" placeholder="活跃度" clearable>
                <el-option label="高活跃" value="high"></el-option>
                <el-option label="中活跃" value="medium"></el-option>
                <el-option label="低活跃" value="low"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="handleFilter">筛选</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-col>
          </el-row>

          <el-table :data="filteredUserDetails" border style="width: 100%">
            <el-table-column prop="nickname" label="用户昵称" width="120"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
            <el-table-column prop="level" label="等级" width="80" align="center">
              <template slot-scope="scope">
                <el-tag :type="getLevelTagType(scope.row.level)">{{ getLevelText(scope.row.level) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="studyTime" label="学习时长" width="120" align="center">
              <template slot-scope="scope">
                {{ formatStudyTime(scope.row.studyTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="questionCount" label="做题数量" width="100" align="center"></el-table-column>
            <el-table-column prop="correctRate" label="正确率" width="100" align="center">
              <template slot-scope="scope">
                <span :style="{ color: scope.row.correctRate >= 80 ? '#67C23A' : scope.row.correctRate >= 60 ? '#E6A23C' : '#F56C6C' }">
                  {{ scope.row.correctRate }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="streakDays" label="连续学习" width="100" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.streakDays >= 7 ? 'success' : scope.row.streakDays >= 3 ? 'warning' : 'info'">
                  {{ scope.row.streakDays }}天
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastLoginTime" label="最后登录" width="180"></el-table-column>
            <el-table-column prop="activityLevel" label="活跃度" width="100" align="center">
              <template slot-scope="scope">
                <el-tag :type="getActivityTagType(scope.row.activityLevel)">{{ getActivityText(scope.row.activityLevel) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="handleViewDetail(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="margin-top: 20px; text-align: right;"
          ></el-pagination>
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户详情对话框 -->
    <el-dialog title="用户学习详情" :visible.sync="userDetailVisible" width="800px">
      <div v-if="selectedUser" class="user-detail">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-section">
              <h4>基本信息</h4>
              <p><strong>昵称：</strong>{{ selectedUser.nickname }}</p>
              <p><strong>邮箱：</strong>{{ selectedUser.email }}</p>
              <p><strong>等级：</strong>{{ getLevelText(selectedUser.level) }}</p>
              <p><strong>注册时间：</strong>{{ selectedUser.createTime }}</p>
              <p><strong>最后登录：</strong>{{ selectedUser.lastLoginTime }}</p>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-section">
              <h4>学习统计</h4>
              <p><strong>总学习时长：</strong>{{ formatStudyTime(selectedUser.studyTime) }}</p>
              <p><strong>做题数量：</strong>{{ selectedUser.questionCount }}</p>
              <p><strong>正确率：</strong>{{ selectedUser.correctRate }}%</p>
              <p><strong>连续学习：</strong>{{ selectedUser.streakDays }}天</p>
              <p><strong>获得徽章：</strong>{{ selectedUser.badges }}个</p>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-section">
              <h4>学习进度</h4>
              <div v-for="(progress, index) in selectedUser.progress" :key="index">
                <p><strong>{{ progress.category }}：</strong>{{ progress.completed }}/{{ progress.total }}</p>
                <el-progress :percentage="(progress.completed / progress.total) * 100" :stroke-width="6"></el-progress>
              </div>
            </div>
          </el-col>
        </el-row>
        
        <div class="detail-section" style="margin-top: 20px;">
          <h4>最近学习记录</h4>
          <el-table :data="selectedUser.recentRecords" style="width: 100%">
            <el-table-column prop="date" label="日期" width="120"></el-table-column>
            <el-table-column prop="category" label="分类" width="120"></el-table-column>
            <el-table-column prop="questionCount" label="做题数" width="100"></el-table-column>
            <el-table-column prop="correctCount" label="正确数" width="100"></el-table-column>
            <el-table-column prop="studyTime" label="学习时长" width="120"></el-table-column>
            <el-table-column prop="score" label="得分" width="80"></el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UserAnalytics',
  data() {
    return {
      stats: {
        totalUsers: 3200,
        activeUsers: 856,
        avgStudyTime: '2.5小时',
        retentionRate: 68.5
      },
      searchKeyword: '',
      filterLevel: '',
      filterActivity: '',
      learningRanking: [
        {
          rank: 1,
          nickname: '张三',
          studyTime: 7200,
          questionCount: 300,
          correctRate: 92
        },
        {
          rank: 2,
          nickname: '李四',
          studyTime: 6800,
          questionCount: 280,
          correctRate: 88
        },
        {
          rank: 3,
          nickname: '王五',
          studyTime: 6500,
          questionCount: 250,
          correctRate: 85
        },
        {
          rank: 4,
          nickname: '赵六',
          studyTime: 6000,
          questionCount: 220,
          correctRate: 82
        },
        {
          rank: 5,
          nickname: '钱七',
          studyTime: 5800,
          questionCount: 200,
          correctRate: 80
        }
      ],
      progressStats: [
        {
          category: 'JavaScript',
          completionRate: 75,
          completed: 45,
          total: 60,
          avgTime: 25,
          color: '#409EFF'
        },
        {
          category: 'Vue.js',
          completionRate: 60,
          completed: 24,
          total: 40,
          avgTime: 30,
          color: '#67C23A'
        },
        {
          category: '数据库',
          completionRate: 40,
          completed: 20,
          total: 50,
          avgTime: 35,
          color: '#E6A23C'
        },
        {
          category: '算法',
          completionRate: 25,
          completed: 15,
          total: 60,
          avgTime: 45,
          color: '#F56C6C'
        }
      ],
      userDetails: [
        {
          id: 1,
          nickname: '张三',
          email: 'zhangsan@example.com',
          level: 'advanced',
          studyTime: 7200,
          questionCount: 300,
          correctRate: 92,
          streakDays: 15,
          lastLoginTime: '2024-01-15 10:30:00',
          activityLevel: 'high',
          createTime: '2023-12-01 09:00:00',
          badges: 8,
          progress: [
            { category: 'JavaScript', completed: 60, total: 60 },
            { category: 'Vue.js', completed: 40, total: 40 },
            { category: '数据库', completed: 45, total: 50 }
          ],
          recentRecords: [
            { date: '2024-01-15', category: '数据库', questionCount: 15, correctCount: 14, studyTime: '45分钟', score: 93 },
            { date: '2024-01-14', category: 'JavaScript', questionCount: 12, correctCount: 11, studyTime: '35分钟', score: 92 },
            { date: '2024-01-13', category: 'Vue.js', questionCount: 10, correctCount: 9, studyTime: '30分钟', score: 90 }
          ]
        },
        {
          id: 2,
          nickname: '李四',
          email: 'lisi@example.com',
          level: 'intermediate',
          studyTime: 6800,
          questionCount: 280,
          correctRate: 88,
          streakDays: 8,
          lastLoginTime: '2024-01-14 15:20:00',
          activityLevel: 'high',
          createTime: '2024-01-01 14:30:00',
          badges: 5,
          progress: [
            { category: 'JavaScript', completed: 45, total: 60 },
            { category: 'Vue.js', completed: 30, total: 40 }
          ],
          recentRecords: [
            { date: '2024-01-14', category: 'JavaScript', questionCount: 10, correctCount: 9, studyTime: '30分钟', score: 90 },
            { date: '2024-01-13', category: 'Vue.js', questionCount: 8, correctCount: 7, studyTime: '25分钟', score: 88 }
          ]
        },
        {
          id: 3,
          nickname: '王五',
          email: 'wangwu@example.com',
          level: 'beginner',
          studyTime: 1800,
          questionCount: 80,
          correctRate: 72,
          streakDays: 3,
          lastLoginTime: '2024-01-13 14:15:00',
          activityLevel: 'medium',
          createTime: '2024-01-10 16:30:00',
          badges: 2,
          progress: [
            { category: 'JavaScript', completed: 20, total: 60 },
            { category: 'Vue.js', completed: 10, total: 40 }
          ],
          recentRecords: [
            { date: '2024-01-13', category: 'JavaScript', questionCount: 8, correctCount: 6, studyTime: '20分钟', score: 75 },
            { date: '2024-01-12', category: 'Vue.js', questionCount: 6, correctCount: 4, studyTime: '15分钟', score: 67 }
          ]
        }
      ],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userDetailVisible: false,
      selectedUser: null
    }
  },
  computed: {
    filteredUserDetails() {
      let result = this.userDetails;
      
      if (this.searchKeyword) {
        result = result.filter(u => 
          u.nickname.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
          u.email.toLowerCase().includes(this.searchKeyword.toLowerCase())
        );
      }
      
      if (this.filterLevel) {
        result = result.filter(u => u.level === this.filterLevel);
      }
      
      if (this.filterActivity) {
        result = result.filter(u => u.activityLevel === this.filterActivity);
      }
      
      return result;
    }
  },
  watch: {
    filteredUserDetails: {
      handler(newVal) {
        this.total = newVal.length;
      },
      immediate: true
    }
  },
  mounted() {
    this.initCharts();
  },
  methods: {
    getLevelTagType(level) {
      const levelMap = {
        beginner: 'info',
        intermediate: 'warning',
        advanced: 'success'
      };
      return levelMap[level] || 'info';
    },
    getLevelText(level) {
      const levelMap = {
        beginner: '新手',
        intermediate: '进阶',
        advanced: '高级'
      };
      return levelMap[level] || level;
    },
    getActivityTagType(activity) {
      const activityMap = {
        high: 'success',
        medium: 'warning',
        low: 'info'
      };
      return activityMap[activity] || 'info';
    },
    getActivityText(activity) {
      const activityMap = {
        high: '高活跃',
        medium: '中活跃',
        low: '低活跃'
      };
      return activityMap[activity] || activity;
    },
    formatStudyTime(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      if (hours > 0) {
        return `${hours}小时${minutes}分钟`;
      }
      return `${minutes}分钟`;
    },
    handleFilter() {
      // 筛选逻辑已在 computed 中处理
    },
    resetFilter() {
      this.searchKeyword = '';
      this.filterLevel = '';
      this.filterActivity = '';
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleViewDetail(row) {
      this.selectedUser = row;
      this.userDetailVisible = true;
    },
    viewFullRanking() {
      // 跳转到完整排行榜页面
      this.$message.info('跳转到完整排行榜页面');
    },
    exportUserData() {
      // 导出用户数据
      this.$message.success('导出成功');
    },
    initCharts() {
      // 这里可以集成 ECharts 来显示图表
      console.log('初始化图表');
    }
  }
}
</script>

<style scoped>
.user-analytics {
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.total-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.active-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.avg-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.retention-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  border-radius: 4px;
}

.rank-badge {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  border-radius: 50%;
  color: white;
  font-weight: bold;
  font-size: 12px;
}

.rank-1 {
  background-color: #f7ba2a;
}

.rank-2 {
  background-color: #c0c4cc;
}

.rank-3 {
  background-color: #b87333;
}

.progress-stats {
  padding: 10px 0;
}

.progress-item {
  margin-bottom: 20px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.progress-label {
  font-weight: bold;
  color: #303133;
}

.progress-percentage {
  color: #409EFF;
  font-weight: bold;
}

.progress-detail {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.user-detail .detail-section {
  margin-bottom: 20px;
}

.user-detail .detail-section h4 {
  margin-bottom: 15px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.user-detail .detail-section p {
  margin: 8px 0;
  color: #606266;
}
</style>
